import React, { useState, useEffect, useMemo, useCallback } from 'react';
import { X } from 'lucide-react';
import { IconButton } from '@/components/ui/Button';
import { ConfirmModal } from './Modal';
import { usePreferencesStore, selectRecentSpaceColors } from '@/stores/preferences';
import { validateSpaceName, getEffectiveTextLength, getSpaceNameError } from '@/lib/utils';
import { cn } from '@/lib/utils';
import { SpaceIconSelector } from '@/components/ui/SpaceIconSelector';
import { SpaceIcon } from '@/components/ui/SpaceIcon';
import { DEFAULT_SPACE_ICON, getSpaceIconColor } from '@/lib/spaceIcons';
import { SpaceColorPicker } from '@/components/ui/SpaceColorPicker';
import type { Space } from '@/types';
import { ScrollContainer } from '@/components/ui/ScrollContainer';
// 导入 TanStack Query hooks
import { useSpaces, useCreateSpace, useUpdateSpace, useDeleteSpace } from '@/hooks/api';

/**
 * 空间创建/编辑模态框组件
 * 功能：新建空间、编辑空间信息、删除空间
 * Props：空间数据（可选，用于编辑模式）、是否打开、关闭回调
 */
interface SpaceModalProps {
    // 空间数据（编辑模式时传入，新建模式时为undefined）
    space?: Space;
    // 模态框是否打开
    isOpen: boolean;
    // 关闭模态框的回调函数
    onClose: () => void;
}

export const SpaceModal: React.FC<SpaceModalProps> = ({
    space,
    isOpen,
    onClose
}) => {
    // 表单状态
    const [name, setName] = useState('');
    // 使用图标ID而非emoji字符
    const [selectedIcon, setSelectedIcon] = useState(DEFAULT_SPACE_ICON);
    // 新增：颜色选择状态
    const [color, setColor] = useState('#334155');
    const [errors, setErrors] = useState<{ name?: string }>({});
    // 图标选择器显示状态
    const [isIconSelectorOpen, setIsIconSelectorOpen] = useState(false);

    // 删除确认状态
    const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);

    // TanStack Query hooks
    const { data: spacesData } = useSpaces();
    const createSpaceMutation = useCreateSpace();
    const updateSpaceMutation = useUpdateSpace();
    const deleteSpaceMutation = useDeleteSpace();

    // 最近颜色 preferences hooks
    const recentColors = usePreferencesStore(selectRecentSpaceColors);
    const addRecentColor = usePreferencesStore(state => state.addRecentSpaceColor);

    // 判断是否为编辑模式
    const isEditMode = !!space;

    // 判断是否正在提交
    const isSubmitting = createSpaceMutation.isPending || updateSpaceMutation.isPending;

    // 初始化表单数据
    useEffect(() => {
        if (space) {
            setName(space.name);
            setSelectedIcon(space.icon);
            // 设置已有空间颜色
            setColor(space.icon_color);
        } else {
            setName('');
            setSelectedIcon(DEFAULT_SPACE_ICON);
            // 重置默认颜色
            setColor('#334155');
        }
        setErrors({});
        // 关闭图标选择器
        setIsIconSelectorOpen(false);
    }, [space, isOpen]);

    // 验证表单
    const validateForm = () => {
        const newErrors: { name?: string } = {};

        // 使用专门的空间名称验证函数
        const validation = validateSpaceName(name);
        if (!validation.isValid) {
            newErrors.name = validation.message;
        }

        setErrors(newErrors);
        return Object.keys(newErrors).length === 0;
    };

    // 名称输入变更（提取逻辑，避免 JSX 内联复杂度）
    const handleNameChange = useCallback((value: string) => {
        setName(value);
        const err = getSpaceNameError(value);
        setErrors(prev => ({ ...prev, name: err }));
    }, []);

    // 名称等效长度与保存按钮禁用状态（避免在 JSX 中写复杂表达式）
    const effectiveNameLength = useMemo(() => getEffectiveTextLength(name), [name]);
    const isSaveDisabled = useMemo(() => {
        return isSubmitting || !name.trim() || !!getSpaceNameError(name);
    }, [isSubmitting, name]);

    // 处理保存操作
    const handleSave = async () => {
        if (!validateForm()) return;

        try {
            if (isEditMode && space) {
                // 编辑模式：更新空间
                await updateSpaceMutation.mutateAsync({
                    spaceId: space.id,
                    data: {
                        name: name.trim(),
                        icon: selectedIcon,
                        icon_color: color || getSpaceIconColor(selectedIcon),
                    }
                });
            } else {
                // 新建模式：创建空间
                // 计算 position（新空间排在最后：取最大 position + 1000）
                const maxPosition = spacesData && spacesData.length > 0
                    ? Math.max(...spacesData.map(s => s.position))
                    : 0;
                const newPosition = maxPosition + 1000;

                await createSpaceMutation.mutateAsync({
                    name: name.trim(),
                    icon: selectedIcon,
                    icon_color: color || getSpaceIconColor(selectedIcon),
                    position: newPosition,
                });
            }

            // 记录最近使用颜色（编辑模式下若修改颜色同样添加）
            addRecentColor(color);

            onClose();
        } catch (error) {
            console.error('保存空间失败:', error);
        }
    };

    // 处理删除操作
    const handleDelete = async () => {
        if (!space) return;

        try {
            await deleteSpaceMutation.mutateAsync(space.id);
            setIsDeleteModalOpen(false);
            onClose();
        } catch (error) {
            console.error('删除空间失败:', error);
        }
    };

    if (!isOpen) return null;

    return (
        <>
            {/* 模态框背景遮罩 */}
            <div className="modal-backdrop">
                {/* 模态框内容容器 */}
                <div
                    className="modal-content max-w-md grid grid-rows-[auto_minmax(0,1fr)_auto] h-[80vh] min-h-[360px] max-h-[680px]"
                >
                    {/* 模态框头部 - 固定在顶部不滚动 */}
                    <div className="flex-shrink-0 flex items-center justify-between p-6 border-b border-gray-200">
                        <h2 className="text-lg font-semibold text-gray-900">
                            {isEditMode ? '编辑空间' : '新建空间'}
                        </h2>
                        <div className="flex items-center gap-2">
                            {/* 关闭按钮 */}
                            <IconButton
                                onClick={onClose}
                                variant="ghost"
                                title="关闭"
                                icon={<X size={16} />}
                            />
                        </div>
                    </div>

                    {/* 模态框主体 - 可滚动内容区域（统一滚动条样式） */}
                    <div className="min-h-0 p-6 overflow-hidden">
                        <ScrollContainer className="h-full">
                            <form onSubmit={(e) => {
                                e.preventDefault();
                                handleSave();
                            }}>
                                {/* 空间名称输入框 */}
                                <div className="mb-6">
                                    <label
                                        htmlFor="space-name"
                                        className="block text-sm font-medium text-gray-700 mb-2"
                                    >
                                        空间名称
                                    </label>
                                    <input
                                        id="space-name"
                                        type="text"
                                        value={name}
                                        onChange={(e) => handleNameChange(e.target.value)}
                                        placeholder="输入空间名称..."
                                        className={cn(
                                            'input',
                                            errors.name && 'border-red-500 focus:border-red-500 focus:ring-red-500'
                                        )}
                                        disabled={isSubmitting}
                                        autoFocus
                                    />
                                    {errors.name && (
                                        <p className="error-message">{errors.name}</p>
                                    )}
                                    {/* 长度计数提示：中文=2，英文=1；超限高亮 */}
                                    <p
                                        className={cn(
                                            'mt-1 text-xs',
                                            effectiveNameLength > 30 ? 'text-red-600' : 'text-gray-400'
                                        )}
                                    >
                                        {effectiveNameLength} / 30
                                    </p>
                                </div>

                                {/* 空间图标选择器 */}
                                <div className="mb-6">
                                    <label className="block text-sm font-medium text-gray-700 mb-3">
                                        选择图标
                                    </label>

                                    {/* 当前选中图标预览 */}
                                    <div className="mb-3">
                                        <button
                                            type="button"
                                            onClick={() => setIsIconSelectorOpen(true)}
                                            disabled={isSubmitting}
                                            className={cn(
                                                'flex items-center gap-3 px-4 py-3 border border-gray-300 rounded-md',
                                                'hover:bg-gray-50 transition-colors cursor-pointer',
                                                'focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-primary-500',
                                                isSubmitting && 'opacity-50 cursor-not-allowed'
                                            )}
                                        >
                                            {/* 使用SpaceIcon组件显示当前选中的图标 */}
                                            <SpaceIcon iconId={selectedIcon} size={20} color={color} />
                                            <span className="text-sm text-gray-700">点击选择图标</span>
                                        </button>
                                    </div>

                                    {/* 图标选择器模态框 */}
                                    {isIconSelectorOpen && (
                                        <div
                                            className="fixed inset-0 z-50 bg-black bg-opacity-50 flex items-center justify-center p-4">
                                            <div
                                                className="bg-white rounded-lg shadow-xl max-w-2xl h-[80vh] min-h-[360px] max-h-[680px] overflow-hidden flex">
                                                <SpaceIconSelector
                                                    selectedIconId={selectedIcon}
                                                    onIconSelect={(iconId) => {
                                                        setSelectedIcon(iconId);
                                                        setIsIconSelectorOpen(false);
                                                    }}
                                                    onClose={() => setIsIconSelectorOpen(false)}
                                                    showCloseButton={true}
                                                />
                                            </div>
                                        </div>
                                    )}
                                </div>

                                {/* 颜色选择器 */}
                                <div className="mb-6">
                                    <label className="block text-sm font-medium text-gray-700 mb-3">
                                        选择颜色
                                    </label>
                                    <SpaceColorPicker
                                        value={color}
                                        onChange={setColor}
                                        disabled={false}
                                        recentColors={recentColors}
                                    />
                                </div>
                            </form>
                        </ScrollContainer>
                    </div>

                    {/* 模态框底部 - 固定在底部不滚动 */}
                    <div
                        className="flex-shrink-0 flex items-center justify-end gap-3 p-6 border-t border-gray-200 bg-gray-50">
                        <button
                            type="button"
                            onClick={onClose}
                            className="btn-secondary"
                            disabled={isSubmitting}
                        >
                            取消
                        </button>
                        <button
                            type="button"
                            onClick={handleSave}
                            disabled={isSaveDisabled}
                            className={cn("btn-primary flex items-center gap-2",
                                isSaveDisabled && 'opacity-50 cursor-not-allowed'
                            )}
                        >
                            {isSubmitting ? '保存中...' : (isEditMode ? '更新' : '创建')}
                        </button>
                    </div>
                </div>
            </div>

            {/* 删除确认模态框 */}
            <ConfirmModal
                open={isDeleteModalOpen}
                onClose={() => setIsDeleteModalOpen(false)}
                title="确认删除空间"
                message={`确定要删除空间 "${space?.name}" 吗？ 警告：删除空间将同时删除其中的所有集合和标签页，此操作不可撤销！`}
                confirmText="删除空间"
                loading={deleteSpaceMutation.isPending}
                onConfirm={handleDelete}
                confirmVariant="danger"
            />
        </>
    );
};
